package com.gsocket.sever;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ListeningThread extends Thread {
    private ServerSocket serverSocket;
    private GSocketSever gSocketSever;
    private boolean isRun;
//    private List<Connection> connections;
    private ThreadPoolExecutor  executor = new ThreadPoolExecutor(10,15,60, TimeUnit.MINUTES,new LinkedBlockingQueue<Runnable>());

    public ListeningThread(ServerSocket serverSocket, GSocketSever gSocketSever) {
        this.serverSocket = serverSocket;
        this.gSocketSever = gSocketSever;
        isRun = true;
//        connections = new ArrayList<Connection>();
    }

    @Override
    public void run() {
        while (isRun) {
            if (serverSocket.isClosed()) {
                closed();
                break;
            }
            try {
                Socket socket = serverSocket.accept();
                Connection connectionThread = new Connection(socket, gSocketSever);
                executor.execute(connectionThread);
//                connectionThread.start();
//                connections.add(connectionThread);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void closed() {
        isRun = false;
//        for (Connection connection: connections) {
//            connection.close();
//        }
        executor.shutdown();
    }

}
